package com.jmemoir.authorize.security.filter;

import com.jmemoir.authorize.security.properties.WhiteUrlProperties;
import com.jmemoir.authorize.security.utils.JwtTokenUtils;
import com.jmemoir.authorize.security.utils.SecurityUtils;
import com.jmemoir.base.common.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Jwt Token 拦截器
 *
 * @author Tellsea
 * @date 2023/8/8
 */
@Component
@RequiredArgsConstructor
public class JwtTokenFilter extends OncePerRequestFilter {

    private final WhiteUrlProperties whiteUrlProperties;
    private final JwtTokenUtils jwtTokenUtils;
    /**
     * 针对需忽略的Url的规则匹配器
     */
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    /**
     * URL 路径匹配的帮助类
     */
    private static final UrlPathHelper URL_PATH_HELPER = new UrlPathHelper();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String lookupPathForRequest = URL_PATH_HELPER.getLookupPathForRequest(request);
        for (String ignoreUrlPattern : whiteUrlProperties.getWhiteUrls()) {
            if (ANT_PATH_MATCHER.match(ignoreUrlPattern, lookupPathForRequest)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        // 从请求头中获取Token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new ServiceException("Token 不存在，请先未登录");
        }
        token = token.substring(7);
        // 解析令牌
        String username = jwtTokenUtils.getUsernameFromToken(token);
        // 判断令牌是否过期
        if (jwtTokenUtils.isTokenExpired(token)) {
            throw new ServiceException("登录过期，请重新登录");
        }
        // 验证令牌
        if (!jwtTokenUtils.validateToken(token, username)) {
            throw new ServiceException("登录过期，令牌无效");
        }
        // 如果Token有效，将用户信息设置到SecurityContextHolder中
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}